﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

using CustomsSystem.BLL;
using CustomsSystem.Model;
using Maticsoft.Common;

namespace WEB.workflowinfo
{
    public partial class workflowinfoEdit : System.Web.UI.Page
    {
        public static int stepIndex = 1;
        public static DataTable dt;
        public Info_workflow model = null;
        public WorkflowManage bll = new WorkflowManage(); 
        /// <summary>
        /// 窗体载入，初始化dataTable
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //dt = new DataTable();
                if (dt != null) { dt = null; stepIndex = 1; }
                gvWordflowInfo.DataSource = dt;
                BindCodeData(ddlGoodsType, "goodType");
                BindCodeData(ddlBusName, "busType");
                BindJobNoData(ddlJobNo);
                if (gvWordflowInfo.DataSource == null)
                {
                    dt = new DataTable();
                    model = new Info_workflow();
                    dt.Columns.Add("stepID", Type.GetType("System.Int32"));
                    dt.Columns.Add("busName", Type.GetType("System.String"));
                    dt.Columns.Add("jobName", Type.GetType("System.String"));
                    dt.Columns.Add("doTimeLimit", Type.GetType("System.String"));
                    dt.Columns.Add("yellowBefore", Type.GetType("System.String"));
                    dt.Columns.Add("remark", Type.GetType("System.String"));
                    //============================================
                    dt.Columns.Add("busType", Type.GetType("System.String"));
                    dt.Columns.Add("jobNo", Type.GetType("System.String"));
                    BindData();
                }
            }
            
        }
        /// <summary>
        /// 增加按钮，添加一行，使某些信息不可编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            //判断是否已存在这个流程名、
            List<Info_workflowMaster> masterList = new List<Info_workflowMaster>();
            masterList=bll.GetModelListMaster("");
            foreach (Info_workflowMaster model in masterList)
            {
                if (model.WKTypeName == tbWKName.Text.Trim())
                {
                    MessageBox.Show(this, "已经存在重名的工作流名称，请修改");
                    return ;
                }
            }
            //先验证
            if (!PageValidate.IsNumber(tbTimeLimit.Text.Trim()))
            {

                MessageBox.Show(this, "时限只能为正整数");
                return;
            }
            else
            {
                if (int.Parse(tbTimeLimit.Text.Trim()) - 1 == -1)
                {
                    MessageBox.Show(this, "时限不能为0");
                }
            }
            if (!PageValidate.IsNumber(tbYellowBefore.Text.Trim()))
            {
                MessageBox.Show(this, "预警时限只能为正整数");
                return;
            }
            if (int.Parse(tbYellowBefore.Text.Trim()) >= int.Parse(tbTimeLimit.Text.Trim()))
            {
                MessageBox.Show(this, "预警时限不能大于等于处理时限");
                return;
            }
            //=======
            ddlGoodsType.Enabled = false;
            ddlSheetType.Enabled = false;
            if (tbWKName.Text == "")
            {
                tbWKName.Text = ddlGoodsType.SelectedItem.Text + ddlSheetType.SelectedItem.Text + "流程";
            }
            tbWKName.Enabled = false;
            //========
            /*if ()//有残留的数据，先删除
            {

            }*/
            if (dt.Rows.Count > 1)
            {
                if (dt.Rows[dt.Rows.Count - 1]["busType"].ToString() == "99")
                {
                    MessageBox.Show(this, "该单已设置完结，如果需要增加请先删除完结步骤");
                    return;
                }
            }
            DataRow dr = dt.NewRow();
            dr["stepID"] = stepIndex++;
            dr["busName"] = ddlBusName.SelectedItem.Text;
            dr["jobName"] = ddlJobNo.SelectedItem.Text;
            dr["doTimeLimit"] = tbTimeLimit.Text;
            int yelloeBefore= int.Parse(tbYellowBefore.Text.Trim());
            yelloeBefore=0-yelloeBefore;
            dr["yellowBefore"] = yelloeBefore;
            dr["remark"] = tbRemark.Text;
            dr["busType"] = ddlBusName.SelectedValue;
            dr["jobNo"] = ddlJobNo.SelectedValue;
            dt.Rows.Add(dr);
            BindData();
        }

        /// <summary>
        /// 将dataTable的值绑定文本框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //protected void gvWordflowInfo_RowEditing(object sender, GridViewEditEventArgs e)
        //{
        //    TextBox curText;

        //    //Response.Write("列数："+e.Row.Cells.Count);
        //    for (int i = 0; i < gvWordflowInfo.Rows[e.NewEditIndex].Cells.Count; i++)
        //    {
        //        if (gvWordflowInfo.Rows[e.NewEditIndex].Cells[i].Controls.Count != 0)
        //        {
        //            curText = gvWordflowInfo.Rows[e.NewEditIndex].Cells[i].Controls[0] as TextBox;
        //            if (curText != null)
        //            {
        //                curText.Text = dt.Rows[e.NewEditIndex][i].ToString();
        //            }
        //        }
        //    }
        //    gvWordflowInfo.EditIndex = e.NewEditIndex;
        //    BindData();
        //}

        //protected void gvWordflowInfo_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        //{
        //    gvWordflowInfo.EditIndex = -1;
        //    BindData();
        //}

        //protected void gvWordflowInfo_RowUpdating(object sender, GridViewUpdateEventArgs e)
        //{
        //    int rowCount=gvWordflowInfo.Rows[e.RowIndex].Cells.Count;
        //    TextBox[] curText=new TextBox[rowCount];
        //    for (int i = 0; i < rowCount; i++)
        //    {
        //        if (gvWordflowInfo.Rows[e.RowIndex].Cells[i].Controls.Count != 0)
        //        {
        //            curText[i] = gvWordflowInfo.Rows[e.RowIndex].Cells[i].Controls[0] as TextBox;
        //            if (curText[i] != null)
        //                dt.Rows[e.RowIndex][i] = curText[i].Text;
        //        }
        //    }
        //    gvWordflowInfo.EditIndex = -1;
        //    BindData();
        //}

        protected void BindData()
        {
            gvWordflowInfo.DataSource = dt;
            gvWordflowInfo.DataBind();
        }

        //重设一个步骤
        protected void btnReset_Click(object sender, EventArgs e)
        {
            
            ddlBusName.SelectedIndex = 0;
            ddlJobNo.SelectedIndex=0;
            tbTimeLimit.Text="";
            tbYellowBefore.Text="";
            tbRemark.Text="";
        }

        /// <summary>
        /// 将gridwiew每一行转成一个model，然后插入数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOk_Click(object sender, EventArgs e)
        {
            if (dt.Rows.Count == 0)
            {
                MessageBox.Show(this, "尚未设置任何信息，不能提交。");
                return;
            }
            CheckComplete();
            Info_workflowMaster modelMaster = new Info_workflowMaster();
            modelMaster.sheetTypeID = Convert.ToInt32(ddlSheetType.SelectedValue);
            modelMaster.goodsTypeID = Convert.ToInt32(ddlGoodsType.SelectedValue);
            //modelMaster.infoWKTypeID = Convert.ToInt32(tbWKNO.Text);
            modelMaster.WKTypeName = tbWKName.Text;
            modelMaster.States = 0; // 默认是保存状态
            int currentWKID;
            currentWKID = bll.AddMaster(modelMaster);
            if (currentWKID == 0)  //插入失败
            {
                MessageBox.Show(this, "请确认所填信息的正确性");
                return ;
            }

            int i;
            for (i = 0; i < dt.Rows.Count; i++)
            {
                //空字符串处理
                model = new Info_workflow();

                model.infoWKTypeID = currentWKID;
                model.stepID = Convert.ToInt32(dt.Rows[i]["stepID"]);
                model.busType = Convert.ToInt32(dt.Rows[i]["busType"]);

                if (dt.Rows[i]["busName"].ToString()== "")
                    model.busName = null;
                else
                    model.busName = dt.Rows[i]["busName"].ToString();

                if (dt.Rows[i]["jobNo"].ToString() == "")
                    model.jobNo = null;
                else
                    model.jobNo = dt.Rows[i]["jobNo"].ToString();

                if (dt.Rows[i]["doTimeLimit"].ToString() == "") 
                    model.doTimeLimit = null;
                else
                    model.doTimeLimit = Convert.ToInt32(dt.Rows[i]["doTimeLimit"].ToString());

                if (dt.Rows[i]["yellowBefore"].ToString() == "")
                    model.yellowBefore = null;
                else
                    model.yellowBefore = Convert.ToInt32(dt.Rows[i]["yellowBefore"].ToString());

                if (dt.Rows[i]["remark"].ToString() == "")
                    model.remark = null;
                else
                    model.remark = dt.Rows[i]["remark"].ToString();

                if (!bll.Add(model)) break;

                //======设置回初始值=========
                
            }

            if (i == dt.Rows.Count)
            {
                MessageBox.ShowAndRedirect(this, "设置成功", "workflowSettingView.aspx");
            }
            else
            {
                MessageBox.Show(this, "设置失败!");
            }
            stepIndex = 1;//设置初始值
            dt = null;
        }

        /// <summary>
        /// 获取制定代码类型绑定到控件上
        /// </summary>
        /// <param name="ddl"></param>
        private void BindCodeData(DropDownList ddl, string codeType)
        {
            CodeManage codeBll = new CodeManage();
            List<Info_code> codeModels = codeBll.GetModelList("codeType='" + codeType + "'");
            foreach (Info_code aCode in codeModels)
            {
                ddl.Items.Add(new ListItem(aCode.codeName, aCode.codeID.ToString()));
            }
        }

        private void BindJobNoData(DropDownList ddl)
        {
            JobManage jobBll = new JobManage();
            List<Info_job> jobModels = jobBll.GetModelList("");
            foreach (Info_job aJob in jobModels)
            {
                ddl.Items.Add(new ListItem(aJob.jobName, aJob.jobNo.ToString()));
            }
        }

        //删除一行 重新编号
        protected void gvWordflowInfo_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            dt.Rows.Remove(dt.Rows[e.RowIndex]);
            //重新编号
            for (int i = 1; i <= dt.Rows.Count; i++)
            {
                dt.Rows[i-1][0] = i.ToString();
            }
            stepIndex--;
            gvWordflowInfo.DataSource = dt;
            gvWordflowInfo.DataBind();
        }

        //添加完结标记
        private void CheckComplete()
        {
            //取最后一条记录
            string busName = dt.Rows[dt.Rows.Count - 1]["busName"].ToString();
            string busType = dt.Rows[dt.Rows.Count - 1]["busType"].ToString();
            if (busName != "完结" && busType != "99")
            {
                DataRow dr = dt.NewRow();
                dr["stepID"] = stepIndex++;
                dr["busName"] = "完结";
                dr["jobName"] = null;
                dr["doTimeLimit"] = null;
                dr["yellowBefore"] = null;
                dr["remark"] = null;
                dr["busType"] = "99";
                dr["jobNo"] = null;
                dt.Rows.Add(dr);
            }
        }

        protected void btnViewTemplate_Click(object sender, EventArgs e)
        {
            Response.Redirect("workflowSettingView.aspx");
        }

    }
}